/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MatriculaAluno.java
 *
 * Created on 17/06/2011, 15:57:37
 */
package matricular;

import utilitarios.ConnectionHelper;
import java.sql.SQLException;
import cadastros.*;
import visao.Telaprincipal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JOptionPane;

/**
 *
 * @author Jean
 */
public class MatriculaAluno extends javax.swing.JFrame {
    
    private Connection conn = null;
    private PreparedStatement pstm = null;
    private ResultSet rs = null;
    
    int codTurma,codCurso,codAluno;

    /** Creates new form MatriculaAluno */
    public MatriculaAluno(Telaprincipal t) {
        initComponents();
        this.setLocationRelativeTo(t);
        conn = ConnectionHelper.getIntance().getConnection();
        
        try{
            pstm = conn.prepareStatement("select * from matricula");
            rs = pstm.getGeneratedKeys();
            while(rs.next()){
                codCurso = rs.getInt("cu_id"); 
                cb_curso.addItem(rs.getString("cu_descricao"));
                
            }
            pstm = conn.prepareStatement("select tu_descricao, tu_id from turma");
            rs = pstm.getGeneratedKeys();
            while(rs.next()){
                codTurma = rs.getInt("tu_id");
                cb_turma.addItem(rs.getString("tu_descricao"));
                
            }
            pstm = conn.prepareStatement("select cu_descricao, cu_id from curso");
            rs = pstm.getGeneratedKeys();
            while(rs.next()){
                codTurma = rs.getInt("tu_id");
                cb_turma.addItem(rs.getString("tu_descricao"));
                
            }
            pstm = conn.prepareStatement("select al_nome, al_id from aluno");
            rs = pstm.getGeneratedKeys();
            while(rs.next()){
                codAluno = rs.getInt("al_id");
                cb_aluno.addItem(rs.getInt("al_id") + " - " + rs.getString("al_nome"));
            }
               
        }catch(SQLException erro){
            JOptionPane.showMessageDialog(null, "Erro ao preencher combo box! "+erro);
        }
  
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        cb_turma = new javax.swing.JComboBox();
        jLabel5 = new javax.swing.JLabel();
        cb_curso = new javax.swing.JComboBox();
        botao_novo = new javax.swing.JButton();
        botao_gravar = new javax.swing.JButton();
        cb_aluno = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18));
        jLabel1.setText("Matrícula Aluno");

        jLabel2.setText("Selecione o Aluno:");

        jLabel4.setText("Turma");

        jLabel5.setText("Curso");

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, cb_curso, org.jdesktop.beansbinding.ELProperty.create("${selectedItem}"), cb_curso, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
        bindingGroup.addBinding(binding);

        botao_novo.setText("Novo");
        botao_novo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botao_novoActionPerformed(evt);
            }
        });

        botao_gravar.setText("Gravar");
        botao_gravar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botao_gravarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(132, 132, 132)
                        .addComponent(jLabel1))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jLabel2)
                            .addComponent(jLabel4)
                            .addComponent(cb_turma, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGap(82, 82, 82)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel5)
                            .addComponent(cb_curso, 0, 189, Short.MAX_VALUE)))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(botao_novo)
                        .addGap(18, 18, 18)
                        .addComponent(botao_gravar)))
                .addGap(86, 86, 86))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(cb_aluno, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(281, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(37, 37, 37)
                .addComponent(jLabel1)
                .addGap(31, 31, 31)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(cb_aluno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(13, 13, 13)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cb_turma, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cb_curso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(39, 39, 39)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(botao_novo)
                    .addComponent(botao_gravar))
                .addContainerGap(50, Short.MAX_VALUE))
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void botao_novoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botao_novoActionPerformed
        // TODO add your handling code here:
      cb_aluno.setSelectedIndex(0);
      cb_curso.setSelectedIndex(0);
      cb_turma.setSelectedIndex(0);
    }//GEN-LAST:event_botao_novoActionPerformed

    private void botao_gravarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botao_gravarActionPerformed
        // TODO add your handling code here:
          try
        {
            String turmaSelecionada = (String) cb_turma.getSelectedItem();
            String cursoSelecionado = (String) cb_curso.getSelectedItem();
            String alunoSelecionado = (String) cb_aluno.getSelectedItem();
            int indice = alunoSelecionado.lastIndexOf("-");
            codAluno = Integer.parseInt(alunoSelecionado.substring(0, indice - 1)); 
            try{
                pstm = conn.prepareStatement("select tu_id from turma where tu_descricao = '?'");
                pstm.setString(1, turmaSelecionada);
                pstm.execute();
                rs = pstm.getResultSet();
                while(rs.next()){
                    codTurma = rs.getInt("tu_id");               
                }
                pstm = conn.prepareStatement("select cu_id from curso where cu_descricao = '?'");
                pstm.setString(1, cursoSelecionado);
                pstm.execute();
                rs = pstm.getResultSet();
                while(rs.next()){
                    codCurso = rs.getInt("cu_id"); 
                }
                
            }catch(SQLException erro){
                JOptionPane.showMessageDialog(null, erro);
            }
            
            pstm = conn.prepareStatement("insert into matricula (ma_idaluno,ma_idturma, ma_idcurso) values (?,?,?)");
            pstm.setInt(1, codAluno);        
            pstm.setInt(2, codTurma);
            pstm.setInt(3, codCurso);
            pstm.execute();
            JOptionPane.showMessageDialog(null, "Gravação realizada com sucesso");
            
            pstm = conn.prepareStatement("select * from matricula");
            rs = pstm.getGeneratedKeys();
            rs.first();
        }catch(SQLException sqlex){
                    JOptionPane.showMessageDialog(null,"Não foi possível gravar dados "+sqlex);
        }
     
    }//GEN-LAST:event_botao_gravarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
               // new MatriculaAluno().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botao_gravar;
    private javax.swing.JButton botao_novo;
    private javax.swing.JComboBox cb_aluno;
    private javax.swing.JComboBox cb_curso;
    private javax.swing.JComboBox cb_turma;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
}
